package com.gxa.security.security;


import com.alibaba.fastjson.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 退出处理
 */
public class TokenLogoutHandler implements LogoutHandler {
    private TokenHandler tokenHandler;
    private RedisTemplate redisTemplate;
    //通过构造方法注入tokenHandler
    public TokenLogoutHandler(TokenHandler tokenHandler,RedisTemplate redisTemplate) {
        this.tokenHandler = tokenHandler;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
         //1. 从header里面获取token
         String token =  request.getHeader("Authorization");
         //2. token不为空，从redis删除token
         if(token != null && !"".equals(token)){
            //从token获取用户名
             String username = tokenHandler.getUserInfoFromToken(token);
             redisTemplate.delete(username);
         }
        response.setContentType("application/json;charset=utf-8");
        Map result = new HashMap<>();
        result.put("code",200);
        result.put("msg","退出登录");
        try {
            response.getWriter().write(JSONObject.toJSONString(result));
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
